﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class CurrencyCreator : System.Web.UI.UserControl
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Administrator"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        string currencyId = null;
        if (Session["currencyId"] != null)
        {
            currencyId = Session["currencyId"].ToString();
        }
        if (currencyId != null && ViewState["isEditing"] == null)
        {
            AddCurrency.Text = "Обновить валюту";
            ViewState["isEditing"] = true;
            var currency = from currencies in db.Currencies where currencies.CurrencyID == Convert.ToInt32(currencyId) select currencies;
            Currency editCurrency = currency.First();
            CurrencyName.Text = editCurrency.Name;
            USDExchangeRate.Text = editCurrency.USDExchangeRate.ToString();
        }
    }
    protected void AddCurrency_Click(object sender, EventArgs e)
    {
        if (ViewState["isEditing"] != null)
        {
            if ((bool)ViewState["isEditing"])
            {
                UpdateCurrency();
            }
        }
        else
        {
            AddNewCurrency();
        }
        Response.Redirect("~/Admin/CurrencyPage.aspx");
    }

    protected void UpdateCurrency()
    {
        string currencyId = null;
        if (Session["currencyId"] != null)
        {
            currencyId = Session["currencyId"].ToString();
        }
        var currency = from currencies in db.Currencies where currencies.CurrencyID == Convert.ToInt32(currencyId) select currencies;
        Currency editCurrency = currency.First();
        editCurrency.USDExchangeRate = Convert.ToDouble(USDExchangeRate.Text);
        editCurrency.Name = CurrencyName.Text;
        db.SubmitChanges();
    }

    protected void AddNewCurrency()
    {
        Currency newCurrency = new Currency();
        newCurrency.Name = CurrencyName.Text;
        newCurrency.USDExchangeRate = Convert.ToDouble(USDExchangeRate.Text);
        db.Currencies.InsertOnSubmit(newCurrency);
        db.SubmitChanges();
    }
}